package com.parkingspace.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.parkingspace.dao.*;
import com.parkingspace.entity.*;
import com.parkingspace.service.IOrderService;
import com.parkingspace.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Gapper
 * @since 2021-05-24
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

	@Resource
	private RabbitTemplate rabbitTemplate;

	@Resource
	private ParkingInformationMapper parkingInformationMapper;

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Resource
	private OrderMapper orderMapper;

	@Resource
	private UserMapper userMapper;
	@Resource
	private CarMapper carMapper;
	@Resource
	private ComplainMapper complainMapper;



	@Override
	public void sendDlx(Long parkingId, Long carUid, String time) {

		QueryWrapper<ParkingInformation> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parking_id",parkingId);

		ParkingInformation parkingInformation = new ParkingInformation();
		parkingInformation.setCarUid(carUid);
		parkingInformation.setParkingStatus(3);

		parkingInformationMapper.update(parkingInformation,queryWrapper);

		String s = String.valueOf((Integer.parseInt(time) * 60000));

		rabbitTemplate.convertAndSend("sunspring_order_exchange","sunspring.order",JSON.toJSONString(parkingId),message -> {
			message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
			message.getMessageProperties().setExpiration(s);
			return message;
		});

	}

	@Override
	public Page<Order> findAllOrder(Long parkingId, String token, long current, long size, Order order, String start, String end) throws Exception {
		List<String> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();

		if (parkingId == null) {
			//检查用户名
			String username = JwtUtils.getUsername(token);
			if (username == null) {
				throw new RuntimeException("请先进行登录!");
			}
			//查询用户ID
			QueryWrapper<User> q = new QueryWrapper<>();
			q.eq("uname", username);
			User user = userMapper.selectOne(q);

			log.info("方法findAllOrder用户的uid为:{}", user.getUid());

			//查询该用户名下的所有车位信息ID
			if (list.size() == 0 || !stringRedisTemplate.opsForValue().get("username").equals(username)) {
				QueryWrapper<ParkingInformation> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("parking_uid", user.getUid());
				List<ParkingInformation> parkingInformations = parkingInformationMapper.selectList(queryWrapper);

				for (ParkingInformation a : parkingInformations) {
					list.add(String.valueOf(a.getParkingId()));
				}
				stringRedisTemplate.opsForList().rightPushAll("list", list);
			} else {
				list = stringRedisTemplate.opsForList().range("list", 0, -1);
			}
			log.info("方法findAllOrder车位的ID集合为:{}", list.toArray());
			//查询该用户名下的所有订单
			queryWrapper1.in("parking_id", list);
		}else {
			//根据车位ID查询
			queryWrapper1.eq("parking_id", parkingId);
		}
			//时间条件
			if (start != null && end != null) {
				queryWrapper1.ge("creat_time", DateUtil.parse(start));
				queryWrapper1.le("creat_time", DateUtil.parse(end));
			}

			//条件查询
			if (order != null) {
				//价格
				if (order.getPrice() != null) {
					queryWrapper1.eq("price", order.getPrice());
				}
				//出租小时
				if (order.getTime() != null) {
					queryWrapper1.eq("time", order.getTime());
				}
				//订单状态
				if (order.getStatus() != null) {
					queryWrapper1.eq("status", order.getStatus());
				}
				//备注模糊查询
				if (order.getRemark() != null) {
					queryWrapper1.like("remark", "%" + order.getRemark() + "%");
				}
			}

			Page<Order> orderPage = orderMapper.selectPage(new Page<Order>(current, size), queryWrapper1);

			return orderPage;
	}





	@Override
	public List<OrderQuery> findAll() {
		List<OrderQuery> orderQueryList = new ArrayList<>();
		QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
//		queryWrapper.lt("time",6);
		List<Order> orderList = orderMapper.findAll(queryWrapper);
		for(Order order : orderList){
			OrderQuery orderQuery = new OrderQuery();
			Long carid = order.getCarid();
			Car car = carMapper.selectById(carid);
			Long uid = car.getUid();
			User user1 = userMapper.selectById(uid);
			ParkingInformation parkingInformation = parkingInformationMapper.selectById(order.getParkingId());
			User lessor = userMapper.selectById(parkingInformation.getParkingUid());
			QueryWrapper<Complain> queryWrapper1 = new QueryWrapper<>();
			queryWrapper1.eq("orderid", order.getOrderid());
			List<Complain> complains = complainMapper.selectList(queryWrapper1);
			orderQuery.setCar(car);
			orderQuery.setRenter(user1);
			orderQuery.setOrder(order);
			orderQuery.setParkingInformation(parkingInformation);
			orderQuery.setLessor(lessor);
			if(complains.size()==0){
				orderQuery.setComplain(new Complain());
			}else {
				orderQuery.setComplain(complains.get(0));
			}
			orderQueryList.add(orderQuery);
		}
		return orderQueryList;
	}

}
